package com.xpwu.secondary.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: caoxue
 * @date: 2019/8/27 8:57
 * @description: 腾讯云短信发送工具类
 * @version: 1.0
 */
@Slf4j
public class QcloudSmsUtils {

    private final static int APP_ID = Integer.parseInt(PropertiesUtil.get("qcloudsms.appid"));

    private final static String APP_KEY = PropertiesUtil.get("qcloudsms.appkey");

    private final static int VERIFY_CODE_TEMPLATE_ID =
            Integer.parseInt(PropertiesUtil.get("qcloudsms.verifycode.templateid"));

    private final static String NATION_CODE = PropertiesUtil.get("qcloudsms.nationcode");

    private final static String SMS_SIGN = PropertiesUtil.get("qcloudsms.smssign");

    /**
     * 指定模板id发送短信
     * @param mobile
     * @return
     */
    public static String sendWithTempalteId(String mobile) {
        try {
            String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
            String[] params = {code};
            SmsSingleSender sender = new SmsSingleSender(APP_ID, APP_KEY);
            SmsSingleSenderResult result = sender.sendWithParam(NATION_CODE, mobile,
                    VERIFY_CODE_TEMPLATE_ID, params, SMS_SIGN, "", "");
            log.info("腾讯云发送短信返回报文：{}", result);
            return result.errMsg;
        } catch (Exception e) {
            log.error("腾讯云短信发送异常", e);
        }
        return null;
    }

    /**
     * 普通发送短信
     * @param mobile
     * @return
     */
    public static String send(String mobile) {
        try {
            String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
            String content = "【腾讯云】您的短信验证码是：{code}";
            content = content.replace("{code}", code);
            SmsSingleSender sender = new SmsSingleSender(APP_ID, APP_KEY);
            SmsSingleSenderResult result = sender.send(0, NATION_CODE, mobile,
                    content, "", "");
            log.info("腾讯云发送短信返回报文：{}", result);
            return result.errMsg;
        } catch (Exception e) {
            log.error("腾讯云短信发送异常", e);
        }
        return null;
    }

    public static void main(String[] args) {
        String s = send("17607127802");
    }

}
